package com.example.jin.handlermessageprogress;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class HandlerMessageProgress extends AppCompatActivity {
    private Button btn_start = null;
    private ProgressBar bar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn_start = (Button) findViewById(R.id.start);
        btn_start.setOnClickListener(new ButtonOnClickLisrener());
        bar = (ProgressBar) findViewById(R.id.pBar);
    }

    class ButtonOnClickLisrener implements Button.OnClickListener{
        @Override
        public void onClick(View v) {
            bar.setVisibility(View.VISIBLE);
            updateBarHandler.post(updateThread);
        }
    }

    Handler updateBarHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            bar.setProgress(msg.arg1);
            updateBarHandler.post(updateThread);
            if(msg.arg1 == 100){
                System.out.println("END");
                updateBarHandler.removeCallbacks(updateThread);
                bar.setVisibility(View.GONE);
            }
        }
    };

    Runnable updateThread= new Runnable() {
        int i = 0;

        @Override
        public void run() {
            System.out.println("Begin Thread" + i);
            if(i > 100){
                i = 0;
            }
            i = i+10;
            Message msg = updateBarHandler.obtainMessage();
            msg.arg1 = i;
            try{
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            updateBarHandler.sendMessage(msg);
            if(i == 100){
                System.out.println("END" + i);
                updateBarHandler.removeCallbacks(updateThread);
            }
        }
    };
}
